<script setup lang="ts">
import {useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import {userStatesStore} from "@/states/userSates.ts";
import { setAvatar, setCurrentUser } from "@/api/user";
import { userStatusEnum } from "@/constants/user";
import { showToast } from "vant";

const router = useRouter()
const userStates = userStatesStore()
const user = ref()
onMounted(async () => {
  await userStates.getUserInfo()
  user.value = userStates.userInfo
})

// 修改
const toEdit = (editKey:string,editName:string,currentValue:string) => {
  router.push({
    path:'/user/edit',
    query:{
      editKey,
      editName,
      currentValue
    }
  })
}

// 性别
const showPicker = ref(false)
const columns = [
  { text: '男', value: '1' },
  { text: '女', value: '0' },
  { text: '保密', value: '2' },
]

const onConfirm = async ({ selectedValues }) => {
  showPicker.value = false
  user.value.gender = selectedValues[0]
  await setCurrentUser(user.value.id,['gender',selectedValues[0]])

};

// 头像修改
const fileList = ref([])
const afterRead = async () => {
  let formData = new FormData();
  formData.append("file", fileList.value[0].file)
  const res = await setAvatar(formData)
  if (res?.data.code === 0) {
      showToast("头像更新成功")
        user.value.avatarUrl = res?.data.data
    } else {
      showToast("头像更新失败" + (res.data.description ? `,${res.data.description}` : ''))
    }
    fileList.value = []

}
</script>

<template>
  <template v-if="user">
    <van-cell title="头像" is-link>
      <van-uploader v-model="fileList" :max-count="1" :after-read="afterRead" preview-size="60px">
        <img style="height: 47px" :src="user.avatarUrl" />
      </van-uploader>
     
    </van-cell>
    <van-cell title="账号" :value="user.userAccount" />
    <van-cell title="昵称" is-link to="/user/edit" :value="user.username"  @click="toEdit('username','昵称',user.username)"/>
    <van-cell title="个性签名" is-link to="/user/edit" :value="user.profile" @click="toEdit('profile','新个性签名',user.profile)"/>
    <van-cell title="标签" is-link to="/user/tags"/>
    <van-cell title="性别" is-link @click="showPicker=true" :value="userStatusEnum[user.gender]"/>
    <van-popup v-model:show="showPicker" round position="bottom">
      <van-picker
        :columns="columns"
        @cancel="showPicker = false"
        @confirm="onConfirm"
      />
    </van-popup>
    <van-cell title="注册时间" :value="user.createTime" />
  </template>
</template>

<style scoped>

</style>